package com.qf.j2112.interceptor;

import com.qf.j2112.annotation.JwtToken;
import com.qf.j2112.util.JwtUtil;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handler1 = (HandlerMethod) handler;
        Method method = handler1.getMethod();
        if(method.isAnnotationPresent(JwtToken.class)){
            JwtToken annotation = method.getAnnotation(JwtToken.class);
            if(annotation.required()){
//                执行认证
                if(token== null){
                    throw new RuntimeException("token wuxiao 请重新登录");
                }
                //获取userId
                String userId = JwtUtil.getUserId(token);
                System.out.println( userId);
                boolean b = JwtUtil.checkToken(token);

            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
